package com.metagurukul.metagranth.service;

import java.util.ArrayList;
import java.util.List;

import com.metagurukul.metagranth.exception.MetaSqlException;
import com.metagurukul.metagranth.model.common.connection.ConnectionPoolFactory;
import com.metagurukul.metagranth.model.dao.TagDAO;
import com.metagurukul.metagranth.vo.Tag;

/**
 * This class handles the operations performed by TagDAO
 * @author Team MetaGranth
 */

public class TagService {
	
	/**
	 * This method gets tag list
	 * @return ArrayList<Tag>
	 * @throws Exception
	 */
	
	public static ArrayList<Tag> getTagsList() throws Exception {
		try {
			// calling TagDAO method to get all the tags
			return TagDAO.getTagsList();
		} catch (Exception exception) {
			throw exception;
		}
	}

	/**
	 * This method gets count of tags in the different questions
	 * @param Tag tag
	 * @return int count
	 * @throws MetaSqlException
	 */
	
	public static int getTagCount(Tag tag) throws MetaSqlException {
		// calling TagDAO method to count tags 
		return TagDAO.getTagCountByTag(tag);
	}

	/**
	 * This method returns all the tags starting from key
	 * @param String key
	 * @return List<String> matched
	 * @throws Exception
	 */
	
	public static List<String> getTagNameList(String key) throws Exception {
		ConnectionPoolFactory connectionPoolFactory = ConnectionPoolFactory.getInstance();
		
		//  inserting all the tags in ArraList of String type
		ArrayList<Tag> tempTag = TagDAO.getTagsList();
		List<String> tagNames = new ArrayList<String>();
		
		// adding tag name in tagNames of all the tags 
		for (Tag tag : tempTag) {
			tagNames.add(tag.getTagName());
		}
		
		int tagListSize = tagNames.size();
		String tagName = null;
		
		// matching is performed after converting lower case
		key = key.toLowerCase();
		
		// all the mathced tags will store all matched tags 
		List<String> matched = new ArrayList<String>();
		
		// if tag name is matched with key then it wil be inserted into list
		for(int i=0; i<tagListSize; i++) {
			// tag name is converted into lower case
			tagName = tagNames.get(i).toLowerCase();
			// if tag name starts with key then added to matched
			if(tagName.startsWith(key)) {
				matched.add(tagNames.get(i));
			}
		}
		return matched;
	}
	
	/**
	 * This method gets all the tags related to a question id 
	 * @param int questionID
	 * @return ArrayList<Tag> tags
	 * @throws MetaSqlException
	 */
	
	public static ArrayList<Tag> getTagsByQuestionId(int questionID) throws MetaSqlException{
		// this array list will contain all the tags
		ArrayList<Tag> tags = new ArrayList<Tag>();
		
		// calling TagDAO to get tags by questionID
		tags = TagDAO.getTagsByQuestionId(questionID);			
		return tags;
	}
}
